import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lishuo
 * Date: 2023-08-11
 * Time: 20:53
 */
@WebServlet("/ShowRequest")
public class ShowRequest extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        StringBuilder result = new StringBuilder();
        // 获取req的版本号
        result.append(req.getProtocol());
        result.append("<br/>");

        // 获取req的请求方法
        result.append(req.getMethod());
        result.append("<br/>");

        // 获取req的uri
        result.append(req.getRequestURI());
        result.append("<br/>");

        // 获取req的url
        result.append(req.getRequestURL());
        result.append("<br/>");

        // 获取请求的query string
        result.append(req.getQueryString());
        result.append("<br/>");

        // 获取请求的ContextPath，ContextPath标识一个webapp，webapp的目录名
        result.append(req.getContextPath());
        result.append("<br/>");

        // 获取请求的ServletPath，ServletPath标识一个类
        result.append(req.getServletPath());
        result.append("<br/>");


        result.append("----------------------------- 分隔线 -------------------------------<br/>");

        // 获取请求头 header 的 key-value
        Enumeration<String> headerNames = req.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            // 获取 name
            String headerName = headerNames.nextElement();
            // 根据 name 获取 value
            String headerValue = req.getHeader(headerName);
            result.append(headerName+":"+headerValue+"<br/>");
        }

        // 在响应中设置上 body 的类型. 方便浏览器进行解析
        resp.setContentType("text/html;charset = utf8");
        resp.getWriter().write(result.toString());
    }
}
